<template>
  <textarea :id="id"></textarea>
</template>

<script>
import Tinymce from 'tinymce/tinymce'
import defaultOptions from './defaultOptions'

window.tinymce.baseURL = '/tinymce'
window.tinymce.suffix = '.min'

/**
 * @ref https://segmentfault.com/a/1190000012791569
 */
export default {
  props: {
    id: {
      type: String,
      default() {
        return `tinymce-${Date.now()}`
      }
    },
    language: {
      type: String,
      default: 'zh_CN'
    },
    options: {
      type: Object,
      default() {
        return defaultOptions
      }
    }
  },
  data() {
    return {
      editor: null
    }
  },
  computed: {
    editorOptions() {
      const options = {
        ...defaultOptions,
        ...this.options,
        language: this.language
      }
      return options
    }
  },
  methods: {
    initEditor() {
      this.editor = Tinymce.init({
        selector: `#${this.id}`,
        ...this.editorOptions,
        setup: editor => {
          editor.on('input change undo redo', () => {
            this.$emit('input', editor.getContent())
          })
        }
      })
    },
    destroyEditor() {
      tinymce.remove(`#${this.id}`)
    }
  },
  watch: {
    language() {
      this.destroyEditor()
      this.initEditor()
    }
  },
  mounted() {
    this.initEditor()
  },
  beforeDestroy() {
    this.destroyEditor()
  }
}
</script>
